package ops;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JPanel;

import ops.view.ApplicationFrame;

public class WindowManager {
	
	private static final String VIEW_PACKAGE = "ops.view";
	
	private HashMap<String, JPanel> panels;
	private ApplicationFrame applicationFrame = null;
	
	protected WindowManager() {
	}

	protected void init() {
		panels = new HashMap<String, JPanel>();

		addAllPanels();
		
		applicationFrame = new ApplicationFrame();
		centerWindow(applicationFrame);
	}

	public void centerWindow(Window window) {
		Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameDimension = window.getSize();
		
		int x = screenDimension.width/2 - frameDimension.width/2;
		int y = screenDimension.height/2 - frameDimension.height/2;
		
		Point center = new Point(x, y);
		
		window.setLocation(center);
	}

	public static WindowManager getInstance() {
		return Application.getInstance().getWindowManager();
	}
	
	public ApplicationFrame getApplicationFrame() {
		return applicationFrame;
	}
	
	private void addAllPanels() {
		add("login.login", "LoginPanel");
		add("login.logout", "LogoutPanel");
		add("login.success", "LoggedUserPanel");
		
		add("register.students", "StudentRegisterPanel");
		add("register.subjects", "SubjectRegisterPanel");
		add("register.classes", "ClassRegisterPanel");
		add("register.teachers", "TeacherRegisterPanel" );
		add("register.courses", "CourseRegisterPanel");
		add("register.term", "TermRegisterPanel");
		
		add("subscription.student", "SubscriptionPanel");
		add("subscription.manage", "ManageSubscriptionPanel");
		
		add("grades.add", "AddGradesPanel");
		
		add("report.crid", "CRIDReportPanel");
		add("report.card", "CardReportPanel");
		add("report.list", "ListReportPanel");
	}
	
	public Map<String, JPanel> getPanels() {
		return Collections.unmodifiableMap(panels);
	}
	
	public JPanel getPanel(String key) {
		return panels.get(key);
	}
	
	@SuppressWarnings("unchecked")
	private void add(String id, String panelName) {
		String fullClassName = VIEW_PACKAGE+"."+panelName;
		
		try {
			Class<JPanel> clazz = (Class<JPanel>) Class.forName(fullClassName);
			JPanel panel = clazz.newInstance();
			
			panels.put(id, panel);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
